package com.bs.sc.base.utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.springframework.web.multipart.MultipartFile;

public class FileUtil {

	/**
	 * 读取文件内容
	 * 
	 * @param filePath
	 * @return
	 */
	public static List<String> readFile(String filePath) {
		File file = new File(filePath);
		BufferedReader br = null;
		List<String> allString = new ArrayList<>();
		try {
			br = new BufferedReader(new FileReader(file));
			String line = "";
			String everyLine = "";
			while ((line = br.readLine()) != null) {
				everyLine = line;
				allString.add(everyLine);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return allString;
	}

	/**
	 * 创建TXT文件
	 * 
	 * @param content
	 * @return
	 */
	public static boolean createTxt(Set<String> content, int flag) {
		boolean b = false;
		BufferedWriter bw = null;
		try {
			String src = "";
			if (flag == 0) {
				src = PropertiesUtil.getPropertiesValue("cf.file");
			} else if (flag == 1) {
				src = PropertiesUtil.getPropertiesValue("cf.classfiy.file");
			}
			System.out.println("=============" + src);
			if (content != null && !content.isEmpty()) {
				File f = new File(src);
				if (f.exists()) {
					f.delete();
				}
				bw = new BufferedWriter(new FileWriter(f));
				Iterator<String> iterator = content.iterator();
				while (iterator.hasNext()) {
					String row = iterator.next();
					if (!iterator.hasNext()) {
						bw.write(row);
					} else {
						bw.write(row + "\r\n");
					}
				}
			}
			b = true;
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (bw != null) {
					bw.flush();
					bw.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return b;
	}

	/**
	 * @param file     文件
	 * @param path     文件存放路径
	 * @param fileName 保存的文件名
	 * @return
	 */
	public static boolean upload(MultipartFile file, String path, String fileName) {
		// 确定上传的文件名
		String realPath = path + "\\" + fileName;
		System.out.println("上传文件：" + realPath);
		File dest = new File(realPath);
		// 判断文件父目录是否存在
		if (!dest.getParentFile().exists()) {
			dest.getParentFile().mkdir();
		}
		try {
			// 保存文件
			file.transferTo(dest);
			return true;
		} catch (IllegalStateException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}
}
